<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta content="text/html; charset=UTF-8" http-equiv="content-type">
    <title>图片变灰</title>

</head>
<body>
<input type="file" id="files" multiple="multiple">
<div id='hk'></div>

<script type="text/javascript">
    var inputElement = document.getElementById("files");
	inputElement.addEventListener("change", handleFiles, false);
    function handleFiles(e){
        if(!location.protocol.match(/^http/)&&navigator.appVersion.indexOf('WebKit')>-1){
            alert('请把文件放在服务器上运行');
        }
        var fileList=e.target.files;
        for (var i = 0; i < fileList.length; i++) {
            var file = fileList[i];
            var imageType = /image.*/;
            if (!file.type.match(imageType)) {
                continue;
            }
            var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e,i){
                    var dataURI=e.target.result;
                    var oImage=new Image();
                    oImage.onload=function(){
                        creatGrayimg(oImage,oImage.width,oImage.height)
                    }
                    oImage.src=dataURI;

                    var oImg=document.createElement('img');
                        oImg.src=dataURI;
                        document.getElementById('hk').appendChild(oImg);
                }
        }
    }
    function creatGrayimg(oimg,w,h){
        var canvas = document.createElement('canvas');
        canvas.width=w;
        canvas.height=h;
        canvas.style.display='';
        var ctx = canvas.getContext("2d");
        ctx.drawImage(oimg,0,0,w,h);
        var imgData= ctx.getImageData(0,0,w,h);
        imgData= gray(imgData);
        ctx.putImageData(imgData,0,0);

        var oImg=document.createElement('img');
            oImg.src=canvas.toDataURL();
            document.getElementById('hk').appendChild(oImg);
    }
    function gray(imgdata){
        var data=imgdata.data;
        for (var i = 0,n =data .length;  i <n; i += 4) {
            var grayVal = (data[i  ]+data[i+1  ]+data[i +2 ])/3 ;
                data[i  ] = grayVal;
                data[i+1  ] =grayVal ;
                data[i+2  ] = grayVal;
        }
        return imgdata;
    }
</script>


</body>
</html>